import 'dart:async';
import 'package:flutter_component_pay/flutter_component_pay.dart';
import 'package:flutter_component_pay/src/utils/abs_utils.dart';
import 'package:tobias/tobias.dart';

/* 
* 支付宝支付
 */
class AbsAlipay {
  static final Tobias _tobias = Tobias();
  static final StreamController<bool> _notInstallStreamController = StreamController.broadcast();
  static final StreamController<bool> _openStreamController = StreamController.broadcast();
  static final StreamController<AbsPayResult> _responseStreamController = StreamController.broadcast();

  /// not install Alipay.
  static Stream<bool> get aliNotInstallEventHandler => _notInstallStreamController.stream;

  /// open answers from Alipay.
  static Stream<bool> get aliOpenEventHandler => _openStreamController.stream;

  /// Response answers from WeChat after payment.
  static Stream<AbsPayResult> get aliResponseEventHandler => _responseStreamController.stream;

  ///
  /// 打开支付宝支付
  ///
  /// * [paramsChannel] 支付参数模型
  ///
  /// 状态码 result_status 说明:
  ///
  /// 9000：请求处理成功。
  ///
  /// 4000：系统异常。
  ///
  /// 6001：用户中途取消。
  ///
  /// 6002：网络连接出错。
  ///
  static void openAlipay(AbsPayParamsChannel paramsChannel) async {
    bool isInstalled = await _tobias.isAliPayInstalled;

    if (!isInstalled) {
      // 未安装支付宝
      _notInstallStreamController.add(true);
      return;
    }

    final body = paramsChannel.param?.body ?? '';
    if (body.isNotEmpty) {
      Map<dynamic, dynamic> json = await _tobias.pay(body);

      // 支付状态提示文本
      String memo = AbsUtils.isBlank(json['memo']) ? '支付失败' : json['memo'];
      // 支付状态 code
      int code = int.parse(json['resultStatus'] ?? '-1');
      // 结果对象
      final payResult = AbsPayResult(
        way: AbsPayWay.aliPay,
        code: code,
        errStr: memo,
      );
      _responseStreamController.add(payResult);
    } else {
      _openStreamController.add(false);
    }
  }

  ///
  /// 销毁相应StreamController
  ///
  static void closeWxStreamControllers() {
    if (_notInstallStreamController.hasListener) {
      _notInstallStreamController.close();
    }
    if (_openStreamController.hasListener) {
      _openStreamController.close();
    }
    if (_responseStreamController.hasListener) {
      _responseStreamController.close();
    }
  }
}
